package uia.alumni.useradm;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Command;



/**
 * Delete a user from the database.
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class DeleteUser extends Command implements Constants {
    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "admin.deleteuser";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction tx;


    public DeleteUser() {
        super(Role.admin);
    }


    /** Delete user data specified by the parameter UID */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        long uid = parseLong(request.getParameter(UID), -1);

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            User user = em.find(User.class, uid);
            if (user != null) {
                em.remove(user);
                log("Deleted user "+uid);
            }
            tx.commit();
        }
        catch (Exception e) {
            addMessage(request, "Delete user failed because:"
                    +e.getMessage());
            log("Delete user failed",e);

        }
        forwardTo(UserAdmin.SERVLET_NAME, request, response);
    }

    public final static long serialVersionUID = 1;

}
